<template>
  <div class="menu-manage">
    <el-row :gutter="20">
      <!-- 左侧菜单树 -->
      <el-col :span="6">
        <el-card>
          <el-tree
            :data="menuTree"
            :props="defaultProps"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
            style="min-height: 400px;"
          >
            <span class="custom-tree-node" slot-scope="{ data }">
              <span>{{ data.name }} <span v-if="data.menuCode">({{ data.menuCode }})</span></span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      <!-- 右侧菜单列表 -->
      <el-col :span="18">
        <el-card>
          <div class="search-bar">
            <el-input v-model="search" placeholder="搜索菜单名称/编码" style="width: 200px;" @keyup.enter="fetchMenus" clearable />
            <el-button type="primary" style="margin-left: 8px;" @click="fetchMenus">查询</el-button>
            <el-button type="primary" @click="openAddDialog" style="float:right;">新增菜单</el-button>
          </div>
          <el-table :data="menuList" style="width: 100%; margin-top: 16px;">
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="menuCode" label="菜单编码" />
            <el-table-column prop="nodeType" label="类型">
              <template slot-scope="scope">
                <span v-if="scope.row.nodeType === 1">文件夹</span>
                <span v-else-if="scope.row.nodeType === 2">页面</span>
                <span v-else>按钮</span>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序号" />
            <el-table-column prop="path" label="路径" />
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <!-- 新增/编辑菜单弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="菜单编码" prop="menuCode">
          <el-input v-model="form.menuCode" autocomplete="off" />
        </el-form-item>
        <el-form-item label="节点类型" prop="nodeType">
          <el-select v-model="form.nodeType" placeholder="请选择" style="width: 100%">
            <el-option label="文件夹" :value="1" />
            <el-option label="页面" :value="2" />
            <el-option label="按钮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="父节点" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父节点" clearable style="width: 100%">
            <el-option label="根节点" :value="0" />
            <el-option
              v-for="item in flatMenuOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="form.sort" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="图标地址" prop="iconUrl">
          <el-input v-model="form.iconUrl" autocomplete="off" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" autocomplete="off" />
        </el-form-item>
        <el-form-item label="页面地址" prop="linkUrl">
          <el-input v-model="form.linkUrl" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMenuTree, getMenuListByParent, addMenu, updateMenu, deleteMenu } from '@/api/menu'

export default {
  name: 'MenuManage',
  data() {
    return {
      search: '',
      menuTree: [],
      menuList: [], // 右侧表格数据
      selectedNode: null, // 当前选中树节点
      defaultProps: { children: 'childMenu', label: 'name' },
      dialogVisible: false,
      dialogTitle: '新增菜单',
      dialogType: 'add',
      form: {
        id: null,
        name: '',
        menuCode: '',
        nodeType: 1,
        parentId: null,
        sort: 0,
        iconUrl: '',
        linkUrl: '',
        path: ''
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        menuCode: [{ required: true, message: '请输入菜单编码', trigger: 'blur' }],
        nodeType: [{ required: true, message: '请选择节点类型', trigger: 'change' }],
        path: [{ required: true, message: '请输入路径', trigger: 'blur' }],
        parentId: [{ required: true, message: '请选择父节点', trigger: 'change' }]
      },
      flatMenuOptions: []
    }
  },
  methods: {
    async fetchMenuTree() {
      const res = await getMenuTree()
      this.menuTree = res.data
    },
    async fetchMenuList(parentId) {
      const res = await getMenuListByParent(parentId)
      this.menuList = res.data
    },
    async handleNodeClick(node) {
      this.selectedNode = node
      await this.fetchMenuList(node.id)
    },
    openAddDialog() {
      this.dialogType = 'add'
      this.dialogTitle = '新增菜单'
      this.form = { id: null, name: '', menuCode: '', nodeType: 1, parentId: this.selectedNode ? this.selectedNode.id : null, sort: 0, iconUrl: '', linkUrl: '', path: '' }
      this.dialogVisible = true
      this.getFlatMenuOptions()
    },
    openEditDialog(data) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑菜单'
      this.form = { ...data }
      this.dialogVisible = true
      this.getFlatMenuOptions()
    },
    async handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        if (this.dialogType === 'add') {
          await addMenu(this.form)
        } else {
          await updateMenu(this.form)
        }
        this.dialogVisible = false
        // 刷新右侧列表和树
        await this.fetchMenuTree()
        await this.getFlatMenuOptions()
        if (this.selectedNode) {
          await this.fetchMenuList(this.selectedNode.id)
        } else {
          await this.fetchMenuList()
        }
        // 新增：通知导航条刷新
        this.$bus && this.$bus.$emit('refresh-navbar')
      })
    },
    async handleDelete(data) {
      this.$confirm('确定要删除该菜单吗？', '提示', { type: 'warning' })
        .then(async () => {
          await deleteMenu(data.id)
          // 刷新右侧列表和树
          await this.fetchMenuTree()
          await this.getFlatMenuOptions()
          if (this.selectedNode) {
            await this.fetchMenuList(this.selectedNode.id)
          } else {
            await this.fetchMenuList()
          }
        })
        .catch(() => {})
    },
    async fetchMenus() {
      // 搜索时可选：树和表都刷新
      await this.fetchMenuTree()
      if (this.selectedNode) {
        await this.fetchMenuList(this.selectedNode.id)
      }
    },
    async getFlatMenuOptions() {
      const res = await getMenuTree()
      this.flatMenuOptions = this.flattenMenuTree(res.data)
    },
    flattenMenuTree(menuTree, level = 0) {
      let result = []
      menuTree.forEach(item => {
        result.push({
          id: item.id,
          name: '　'.repeat(level) + item.name
        })
        if (item.childMenu && item.childMenu.length > 0) {
          result = result.concat(this.flattenMenuTree(item.childMenu, level + 1))
        }
      })
      return result
    }
  },
  mounted() {
    this.fetchMenuTree()
    this.getFlatMenuOptions()
    this.fetchMenuList()
  }
}
</script>

<style scoped>
.menu-manage {
  padding: 24px;
}
.search-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
</style> 